using System;
using 综合同步;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System.Net.WebSockets;
using Microsoft.AspNetCore.Hosting;
using System.IO;

public class WsData
{
    static object mutex = new object();
    static bool bWebSocketBegin = false;
    public static bool WebSocketBegin{
        get {
            lock(mutex) return bWebSocketBegin;
        }
        set{
            lock(mutex) bWebSocketBegin = value;
        }
    }
    public static async Task BroadCastData(WebSocket webSocket,int idx){
        bool bFirst = true;
        WebSocketBegin = true;
        byte[] data = null, buffer = new byte[1];
        WebSocketReceiveResult result = null;
        while((result ==null||!result.CloseStatus.HasValue) && webSocket.State == WebSocketState.Open){
            try{
                RedisClientBll.realTimeData.TryPeek(out data);
                if(data==null||(data.Length>256&&
                    (Encoding.Default.GetString(data, 0, 256).Contains("视频")&&idx!=1)&&
                    (Encoding.Default.GetString(data, 0, 256).Contains("红外")&&idx!=2))
                ){
                    Thread.Sleep(1);
                    continue;
                }
                if(!RedisClientBll.realTimeData.TryDequeue(out data))
                    continue;
                if(bFirst){
                    bFirst = false;
                    uint width = BitConverter.ToUInt32(data, 256 + 0 * sizeof(int));
                    uint height = BitConverter.ToUInt32(data, 256 + 1 * sizeof(int));
                    byte[] frame_header = new uint[]{0xffaaffcc,1,8,width,height}.
                        SelectMany(o=>BitConverter.GetBytes(o)).ToArray();
                    await webSocket.SendAsync(new ArraySegment<byte>(frame_header),
                        WebSocketMessageType.Binary,true,CancellationToken.None);
                }
                //去掉redis数据中的包头
                data = data.Skip(256 + 6 * sizeof(int)+2*sizeof(Int64)).ToArray();
                uint[] header = new uint[]{0xffaaffcc,2,(uint)data.Length};
                byte[] send_data = header.SelectMany(o=>BitConverter.GetBytes(o)).Concat(data).ToArray();
                await webSocket.SendAsync(new ArraySegment<byte>(send_data),
                    WebSocketMessageType.Binary,true,CancellationToken.None);
                //接收心跳
                result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                Thread.Sleep(16);
            }catch(Exception e){
                FileLogOperator.Info(e.Message);
            }
        }
        WebSocketBegin = false;
        while(RedisClientBll.realTimeData.TryDequeue(out data));
        await webSocket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable,"close",CancellationToken.None);
    }
}